import os
import time

from django.db.models import Q
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from rest_framework.viewsets import ModelViewSet

from cards.models import Card, RetailerCard, CardDepositRecord, GiftCard, UserGiftCard, CardConsumeRecord, SampleCard, \
    ClientSampleRecord, BalanceBill
from wine import settings
from .serializers import CardSerializer, RetailerCardSerializer, CardDepositRecordSerializer, GiftCardSerializer, \
    UserGiftCardSerializer, CardConsumeRecordSerializer, SampleCardSerializer, ClientSampleRecordSerializer, \
    BalanceBillSerializer


class CardListAPIView(ListAPIView):
    """会员卡列表"""
    permission_classes = ()
    serializer_class = CardSerializer
    queryset = Card.objects.all()
    pagination_class = None


class RetailerCardListAPIView(ListAPIView):
    """商家会员卡列表"""
    permission_classes = ()
    serializer_class = RetailerCardSerializer
    queryset = RetailerCard.objects.filter(ack=1)
    pagination_class = None


class CardViewSet(ModelViewSet):
    """制卡"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = Card.objects.all()
    serializer_class = CardSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)

        if name:
            queryset = queryset.filter(name__contains=name)

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class RetailerCardViewSet(ModelViewSet):
    """商家卡"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = RetailerCard.objects.all()
    serializer_class = RetailerCardSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)

        retailer_id = self.request.query_params.get("retailer_id", None)

        if retailer_id:
            queryset = queryset.filter(retailer_id=int(retailer_id))

        if name:
            queryset = queryset.filter(card__name__contains=name)

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class CardImageUploadAPIView(APIView):
    authentication_classes = ()
    permission_classes = ()

    def post(self, request, *args, **kwargs):
        # 接收文件
        content_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp', 'image/tiff']
        file = request.FILES.get('image', None)
        card_id = request.data.get("card_id", None)
        if file and file.content_type in content_types:
            print(file, card_id)
            if card_id:
                upload_path = Card.image.field.upload_to
                dirs = os.path.join(settings.MEDIA_ROOT, upload_path)
                if not os.path.exists(dirs):
                    os.makedirs(dirs)

                file_info = file.name.rsplit(".", 1)
                old_file_name = file_info[0]
                file_suffix = file_info[1]
                file_name = '{0}_{1}.{2}'.format(old_file_name, int(time.time()), file_suffix)
                file_path = os.path.join(dirs, file_name)

                with open(file_path, 'wb') as f:
                    for chunk in file.chunks():
                        f.write(chunk)

                file_url = '{0}{1}'.format(upload_path, file_name)

                data = {
                    'image': file_url,
                }

                obj, created = Card.objects.update_or_create(id=int(card_id), defaults=data)
                dict_obj = {
                    "id":   obj.id,
                    "image": "{}://{}{}".format(request.scheme, request.get_host(), obj.image.url),
                }

                msg = {
                    "status_code": status.HTTP_200_OK,
                    "file": dict_obj,
                }
                return Response(msg)

        return Response({"status_code": status.HTTP_401_UNAUTHORIZED, "message": "上传失败!"})


class CardImageDestroyAPIView(APIView):
    """删除图片"""
    authentication_classes = ()
    permission_classes = ()

    def post(self, request, *args, **kwargs):
        card_id = kwargs.get("card_id", None)
        if card_id:
            Card.objects.filter(id=int(card_id)).update(image=None)
            msg = {
                "status_code": status.HTTP_200_OK,
            }
            return Response(msg)

        return Response({"status_code": status.HTTP_401_UNAUTHORIZED, "message": "删除失败!"})


class CardDepositRecordViewSet(ModelViewSet):
    """商家购卡表"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = CardDepositRecord.objects.all()
    serializer_class = CardDepositRecordSerializer

    def get_queryset(self):
        queryset = super().get_queryset()
        name = self.request.query_params.get("name", None)
        retailer_id = self.request.query_params.get("retailer_id", None)
        out_trade_no = self.request.query_params.get("out_trade_no", None)
        telephone = self.request.query_params.get("telephone", None)
        search_date = self.request.query_params.getlist("search_date[]", None)

        if retailer_id:
            queryset = queryset.filter(retailer_id=int(retailer_id))

        if name:
            queryset = queryset.filter(Q(name__contains=name) | Q(openid__contains=name))

        if out_trade_no:
            queryset = queryset.filter(out_trade_no__contains=out_trade_no)

        if telephone:
            queryset = queryset.filter(telephone=telephone)

        if search_date and len(search_date) == 2:
            queryset = queryset.filter(pay_time__date__range=(search_date[0], search_date[1]))

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class GiftCardViewSet(ModelViewSet):
    """赠送卡"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = GiftCard.objects.all()
    serializer_class = GiftCardSerializer

    def get_queryset(self):
        queryset = super().get_queryset()
        name = self.request.query_params.get("name", None)
        retailer_id = self.request.query_params.get("retailer_id", None)
        order_no = self.request.query_params.get("order_no", None)
        search_date = self.request.query_params.getlist("search_date[]", None)

        if retailer_id:
            queryset = queryset.filter(retailer_id=int(retailer_id))

        if name:
            queryset = queryset.filter(Q(name__contains=name) | Q(openid__contains=name) | Q(customer_name__contains=name)|Q(customer_openid__contains=name))

        if order_no:
            queryset = queryset.filter(order_no__contains=order_no)

        if search_date and len(search_date) == 2:
            queryset = queryset.filter(update_time__date__range=(search_date[0], search_date[1]))

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class UserGiftCardViewSet(ModelViewSet):
    """客户会员卡"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = UserGiftCard.objects.all()
    serializer_class = UserGiftCardSerializer

    def get_queryset(self):
        queryset = super().get_queryset()
        name = self.request.query_params.get("name", None)
        retailer_id = self.request.query_params.get("retailer_id", None)

        search_date = self.request.query_params.getlist("search_date[]", None)

        if retailer_id:
            queryset = queryset.filter(r_card__retailer_id=int(retailer_id))

        if name:
            queryset = queryset.filter(Q(name__contains=name) | Q(openid__contains=name))

        if search_date and len(search_date) == 2:
            queryset = queryset.filter(update_time__date__range=(search_date[0], search_date[1]))

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class CardConsumeRecordViewSet(ModelViewSet):
    """客户会员卡消费记录"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = CardConsumeRecord.objects.all()
    serializer_class = CardConsumeRecordSerializer

    def get_queryset(self):
        queryset = super().get_queryset()
        name = self.request.query_params.get("name", None)
        retailer_id = self.request.query_params.get("retailer_id", None)
        r_card = self.request.query_params.get("r_card", None)
        search_date = self.request.query_params.getlist("search_date[]", None)

        if retailer_id:
            queryset = queryset.filter(retailer_id=int(retailer_id))

        if name:
            queryset = queryset.filter(Q(name__contains=name) | Q(openid__contains=name) | Q(r_name__contains=name) | Q(r_openid__contains=name))

        if r_card:
            queryset = queryset.filter(r_card_id=int(r_card))

        if search_date and len(search_date) == 2:
            queryset = queryset.filter(update_time__date__range=(search_date[0], search_date[1]))

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class SampleCardViewSet(ModelViewSet):
    """客户品鉴卡"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = SampleCard.objects.all()
    serializer_class = SampleCardSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)

        if name:
            queryset = queryset.filter(Q(name__contains=name) | Q(openid__contains=name))

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class ClientSampleRecordViewSet(ModelViewSet):
    """客户品鉴卡消费记录"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = ClientSampleRecord.objects.all()
    serializer_class = ClientSampleRecordSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)

        retailer_id = self.request.query_params.get("retailer_id", None)

        if retailer_id:
            queryset = queryset.filter(retailer_id=int(retailer_id))

        if name:
            queryset = queryset.filter(Q(name__contains=name) | Q(openid__contains=name))

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class BalanceBillViewSet(ModelViewSet):
    """结算单"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = BalanceBill.objects.all()
    serializer_class = BalanceBillSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        retailer_id = self.request.query_params.get("retailer_id", None)

        if retailer_id:
            queryset = queryset.filter(retailer_id=int(retailer_id))

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)
